<?php

namespace app\controllers;

use app\models\AdminUser;
use app\models\Announce;
use app\models\Baoxiao;
use app\models\Customer;
use app\models\CustomerRefer;
use app\models\CustomerUpdateLog;
use app\models\Department;
use app\models\EmailModel;
use app\models\Inquiry;
use app\models\InquiryType;
use app\models\LandEmail;
use app\models\Login_log;
use app\models\Staff;
use app\service\BroadcastService;
use app\service\CustomerService;
use app\service\LoginService;
use app\service\StaffService;
use yii;
use yii\helpers\Url;

class SettingController extends CommonController
{
    use \app\lib\Redis;

    public $layout               = false;
    public $enableCsrfValidation = false;

    public function actionIndex()
    {
        if ($this->user  ['role'] == 13) {
            return $this->redirect('/setting/top10-product');
        }
        $model                          = new Login_log();
        $list                           = $model->get_login_list();
        yii::$app->view->params['list'] = $list;
        $service                        = new BroadcastService();
        $group                          = $service->get_staff_group($this->user['job_number']);
        $broadcast_list                 = $service->get_broadcast($group);
        // echo json_encode($broadcast_list);exit;
        yii::$app->view->params['broadcast'] = $broadcast_list;
        //通告列表
        $model = new Announce();
        $list  = $model->all();
        return $this->render('index', ['list' => $list]);
    }

    /**
     * 公告信息
     */
    public function actionPost()
    {
        $id = yii::$app->request->get('id');
        if (!is_numeric($id) || $id < 0) {
            return \json_encode(['code' => 0, 'msg' => '不存在记录']);
        }

        $model = new yii\db\Query();
        $re    = $model->select('*')->from('jingsourcing_announce as a')
            ->join('left join', 'jingsourcing_staff b', 'a.staff=b.job_number')
            ->where(['a.id' => $id])
            ->limit(1)->one();
        return $this->render('post', ['info' => $re]);
    }

    /**客户列表
     * @return string
     */
    public function actionCustomer()
    {
        $p                        = is_numeric(yii::$app->request->get('p')) ? yii::$app->request->get('p') : 1;
        $s                        = is_numeric(yii::$app->request->get('s')) ? yii::$app->request->get('s') : 15;
        $where['customer_name']   = yii::$app->request->get('customerName') ? trim(yii::$app->request->get('customerName')) : "";
        $where['property']        = yii::$app->request->get('property');
        $where['refer']           = yii::$app->request->get('refer');
        $where['customer_group']  = yii::$app->request->get('customer_group');
        $where['follow_man']      = yii::$app->request->get('follow_man');
        $where['customer_status'] = yii::$app->request->get('customer_status');
        $where['email']           = trim(yii::$app->request->get('email'));
        $where['number']          = trim(yii::$app->request->get('number'));
        $show                     = yii::$app->request->get('show');
        if ($this->user['role'] != 1 && $this->user['role'] != 2) {
            $where['follow_man'] = $this->user['job_number'];
        }
        $model = new Customer();
        if ($show) {
            $customerLogModel = new CustomerUpdateLog();
            $list             = $customerLogModel->getListByParam(['status' => 1]);
            $tmp              = [];
            foreach ($list as $v) {
                $tmp[] = $v['customer_id'];
            }
            $where['need_update'] = $tmp;
        }

        //客户来源
        $customerReferModel = new CustomerRefer();
        $refer_list         = $customerReferModel->list();
        //客户状态
        $status_list = $model->get_all_customer_status();
        //跟进人
        $saleman_model = new Staff();
        $saleman_list  = $saleman_model->get_all_saleman();

        //客户分组
        $group_list = $model->get_all_customer_group();

        $size                                = $model->get_customer_size(($where));
        yii::$app->view->params['pagecount'] = $size;
        $page                                = $size ? ceil($size / $s) : 1;

        $base_url                       = Url::to(['setting/customer']) . $this->get_base_url();
        yii::$app->view->params['page'] = ['curr' => $p, 'page' => $page, 'base_url' => $base_url];
        $list                           = $model->get_customer_list($p, $s, $where);
        //查看是否有更新记录
        $arr = [];
        foreach ($list as $v) {
            $arr[] = (int) $v['id'];
        }
        $model             = new CustomerUpdateLog();
        $customer_log_list = $model->list($arr);
//        echo json_encode($customer_log_list);exit;
        foreach ($list as $k => $v) {
            $tmp = json_decode($v['follow_man'], true);
            if (is_array($tmp)) {
                $list[$k]['follow_man'] = $tmp;
            } else {
                $list[$k]['follow_man'] = (array) $v['follow_man'];
            }
        }
        $data                      = [];
        $data['group_list']        = $group_list;
        $data['saleman_list']      = $saleman_list;
        $data['status_list']       = $status_list;
        $data['refer_list']        = $refer_list;
        $data['list']              = $list;
        $data['customer_log_list'] = $customer_log_list;
        $data['role']              = $this->user['role'];
        return $this->render('customer', ['data' => $data]);
    }

    public function actionCustomer_add()
    {
        if (yii::$app->request->isPost) {
            $data              = $_POST['data'];
            $data['create_at'] = date('Y-m-d');
            unset($data['link_man']);
            unset($data['customer_group']);
            unset($data['customer_status']);
            unset($data['linkman_phone']);
            unset($data['linkman_remark']);
            $data['time']   = time();
            $model          = new Customer();
            $data['number'] = $model->generateNum();
            try {
                $re = $model->insert($data);
            } catch (Exception $e) {
                return json_encode(['code' => 1, 'msg' => json_encode($e->getMessage())]);
            }

            if ($re) {
                echo json_encode(['code' => 1, 'msg' => '添加成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '添加失败，请重试']);
            }
        }
    }

    /**更新客户
     * @return string
     */
    public function actionUpdate_customer()
    {
        $data = yii::$app->request->post('data');
        if ($data) {
            $arr   = json_decode($data, true);
            $model = new CustomerUpdateLog();
            if ($model->insert(['customer_id' => $arr['id'], 'sql' => $data])) {
                return json_encode(['code' => 1, 'msg' => '添加成功,等待审核通过']);
            } else {
                return json_encode(['code' => 0, 'msg' => '添加失败,请重试']);
            }
        }

    }

    public function actionInquiry2()
    {
        return $this->render('inquiry2');
    }

    public function actionInquiry2List()
    {
        $where = [];
        if ($this->user['role'] != 1 && $this->user['role'] != 2) {
            $where['follow_man'] = (int) $this->user['job_number'];
        }
        $db = new yii\db\Query();
        $db->select('a.*,b.customer_name,b.number,b.email')->from('jingsourcing_new_inquiry as a')
            ->leftJoin('jingsourcing_customer as b', 'a.user_id=b.id');

        if (!empty($where['follow_man'])) {
            $db->andWhere(['!=', 'b.follow_man', '']);
            $db->andWhere("JSON_CONTAINS(b.follow_man,'\"{$where['follow_man']}\"')");
        }

        $list = $db->orderBy(['a.time' => SORT_DESC])->all();
        return \json_encode(['list' => $list, 'total' => count($list)]);
    }

    /**
     * 审核客户
     * @return string
     *
     */
    public function actionVerify_update_customer()
    {
        $model                          = new CustomerUpdateLog();
        $list                           = $model->list_all();
        yii::$app->view->params['list'] = $list;
        return $this->render('verify_update_customer');
    }

    /**上传客户excel
     * @return bool
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     */
    public function actionUpload_customer_excel()
    {
        $path = $this->get_folder();

        $file = $_FILES['file'];

        if ($file) {
            $suffix = explode(".", $file['name']);
            if (!($suffix[1] == 'xls' || $suffix[1] == 'xlsx')) {
                echo json_encode(['code' => 0, 'msg' => '不是excel文件']);
                return false;
            }
            $real_path = $path . DIRECTORY_SEPARATOR . "customer_" . time() . "." . $suffix[1];
            $re        = move_uploaded_file($file['tmp_name'], $real_path);
            if ($re) {
                //获取excel对象
                $objPHPExcel   = $this->get_excel($real_path, $suffix[1]);
                $sheet         = $objPHPExcel->getSheet(0);
                $highestRow    = $sheet->getHighestRow();
                $highestColumn = $sheet->getHighestColumn();

                //从第二行开始读取
                for ($j = 2; $j <= $highestRow; $j++) {
                    $num = $objPHPExcel->getActiveSheet()->getCell("A$j")->getValue();
                    if ($num) {
                        $data[$j][] = $num;
                        $data[$j][] = $objPHPExcel->getActiveSheet()->getCell("B$j")->getValue();
                        $data[$j][] = $objPHPExcel->getActiveSheet()->getCell("C$j")->getValue();
                        $data[$j][] = $objPHPExcel->getActiveSheet()->getCell("D$j")->getValue();
                        $data[$j][] = $objPHPExcel->getActiveSheet()->getCell("E$j")->getValue();
                        $data[$j][] = $objPHPExcel->getActiveSheet()->getCell("F$j")->getValue();
                        $data[$j][] = $objPHPExcel->getActiveSheet()->getCell("G$j")->getValue();
                        $data[$j][] = $objPHPExcel->getActiveSheet()->getCell("H$j")->getValue();
                        $data[$j][] = $objPHPExcel->getActiveSheet()->getCell("I$j")->getValue();
                        $obj        = $objPHPExcel->getActiveSheet()->getCell("J$j")->getValue();
                        $data[$j][] = is_object($obj) ? $obj->__toString() : $obj;
                        $data[$j][] = $objPHPExcel->getActiveSheet()->getCell("K$j")->getValue();
                        $data[$j][] = $objPHPExcel->getActiveSheet()->getCell("L$j")->getValue();
                        $data[$j][] = $objPHPExcel->getActiveSheet()->getCell("M$j")->getValue();
                        $data[$j][] = $objPHPExcel->getActiveSheet()->getCell("N$j")->getValue();
                        $data[$j][] = $objPHPExcel->getActiveSheet()->getCell("O$j")->getValue();
                    }
                }
                //存入数据库
                $db = new \app\models\Customer();
                $re = $db->insert_customer($data);
                if ($re) {
                    echo json_encode(['code' => 1, 'msg' => '添加成功']);
                } else {
                    echo json_encode(['code' => 0, 'msg' => '添加失败,请重试']);
                }
            }
        } else {
            echo 'fail';
        }
    }

    /**
     * 职员管理
     */
    public function actionStaff()
    {
        $model                          = new Staff();
        $where                          = [];
        $where['status']                = (int) yii::$app->request->get('status', 0);
        $sort                           = yii::$app->request->get('sort', 'DESC');
        $sort                           = $sort == 'DESC' ? SORT_DESC : SORT_ASC;
        $staff_list                     = $model->all($where, false, false, ['date' => $sort]);
        yii::$app->view->params['list'] = $staff_list;
        return $this->render('staff');
    }

    public function actionEmail()
    {
        $model = new EmailModel();
        $list  = $model->all();
        return $this->render('email', ['list' => $list]);
    }

    public function actionMailUpload()
    {
        if (!yii::$app->request->isPost) {
            return json_encode(['code' => 0, 'msg' => '非法请求']);
        }
        $id = yii::$app->request->post('id');
        if ($id) {
            $data['detail']    = yii::$app->request->post('data');
            $data['create_at'] = time();
            yii::$app->db->createCommand()->update('jingsourcing_email', $data, ['id' => $id])->execute();
        } else {
            $data['name']      = yii::$app->request->post('name');
            $data['detail']    = yii::$app->request->post('data');
            $data['create_at'] = time();
            yii::$app->db->createCommand()->insert('jingsourcing_email', $data)->execute();
        }
        return json_encode(['code' => 1, 'msg' => 'success']);
    }

    public function actionStaff_add()
    {
        $model                           = new Department();
        $group                           = $model->all();
        yii::$app->view->params['group'] = $group;
        return $this->render('staff_add');
    }

    public function actionStaff_add_act()
    {
        //带工号
        $model = new Staff();
        $data  = $_POST;
        if (is_numeric($_POST['job_number'])) {
            $job_number = $_POST['job_number'];
            $re         = $model->one(['job_number' => $job_number]);
            if ($re) {
                return json_encode(['code' => 0, 'msg' => '当前工号已存在']);
            }
        } else {
            //生成一个工号
            $max                = $model->get_max_job_number();
            $data['job_number'] = $max['num'];
        }
        $re = $model->insert($data);
        if ($re) {
            $output = ['code' => 1, 'msg' => '添加成功'];
        } else {
            $output = ['code' => 0, 'msg' => '添加失败，请重试'];
        }
        return json_encode($output);
    }

    /**员工离职操作
     * @throws yii\db\Exception
     */
    public function actionStaff_del()
    {
        $id    = yii::$app->request->post('id');
        $model = new Staff();
        $re    = $model->save(['status' => 1], ['id' => $id]);
        if ($re) {
            echo json_encode(['code' => 1, 'msg' => '更新成功']);
        } else {
            echo json_encode(['code' => 0, 'msg' => '更新失败，请重试']);
        }
    }

    /**删除员工操作
     * @throws yii\db\Exception
     */
    public function actionStaff_real_del()
    {
        if (yii::$app->request->isPost) {
            $id    = yii::$app->request->post('id');
            $model = new Staff();
            $re    = $model->delete(['id' => $id]);
            if ($re) {
                echo json_encode(['code' => 1, 'msg' => '删除成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '删除失败，请重试']);
            }
        } else {
            echo json_encode(['code' => 0, 'msg' => '非法请求']);
        }
    }

    public function actionStaffEdit()
    {
        if (!yii::$app->request->isPost) {
            return json_encode(['code' => 0, 'msg' => '非法请求']);
        }

        $data['wechat'] = yii::$app->request->post('wechat');
        $data['avatar'] = yii::$app->request->post('avatar');
        $data['skype']  = yii::$app->request->post('skype');
        $re             = yii::$app->db->createCommand()->update('jingsourcing_staff', $data, ['job_number' => $this->user['job_number']])->execute();
        if ($re) {
            return json_encode(['code' => 1, 'msg' => '上传成功']);
        } else {
            return json_encode(['code' => 0, 'msg' => '上传失败,请重试']);
        }
    }

    /**通过参数更新业务员
     * @throws yii\db\Exception
     */
    public function actionStaff_edit_by_column()
    {
        $id     = yii::$app->request->post('id');
        $column = yii::$app->request->post('column');
        $value  = yii::$app->request->post('v');
        if (is_numeric($id)) {
            $re = yii::$app->db->createCommand()
                ->update(yii::$app->db->tablePrefix . "staff", [$column => $value], ['id' => $id])
                ->execute();
            if ($re) {
                echo json_encode(['code' => 1, 'msg' => '更新成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '更新失败，请重试']);
            }
        }
    }

    /**现在员工信息excel
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function actionDownload_staff()
    {
        $model       = new Staff();
        $list        = $model->get_staff_list();
        $objPHPExcel = new \PHPExcel();
        //设置第一栏

        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '入职日期')
            ->setCellValue('B1', '工号')
            ->setCellValue('C1', '中文名')
            ->setCellValue('D1', '英文名')
            ->setCellValue('E1', '手机号')
            ->setCellValue('F1', '农商银行卡')
            ->setCellValue('G1', '邮箱')
            ->setCellValue('H1', '服务器编号')
            ->setCellValue('I1', '所属部门')
            ->setCellValue('J1', '状态');

        foreach ($list as $k => $v) {
            $num = $k + 2;
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A' . $num, $v['date'])
                ->setCellValue('B' . $num, $v['job_number'])
                ->setCellValue('C' . $num, $v['name'])
                ->setCellValue('D' . $num, $v['en_name'])
                ->setCellValue('E' . $num, $v['phone'])
                ->setCellValue('F' . $num, $v['bank_num'])
                ->setCellValue('G' . $num, $v['email'])
                ->setCellValue('H' . $num, $v['server_num'])
                ->setCellValue('I' . $num, $v['group_name']);
            if ($v['status'] == 0) {
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('J' . $num, '在职');
            } else {
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('J' . $num, '离职');
            }
        }
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setAutoSize(true);

        $name = '员工信息';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $name . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
    }

    /**询盘添加页面
     * @return string
     */
    public function actionInquiry()
    {

        $model                             = new Staff();
        $list                              = $model->get_all_saleman();
        yii::$app->view->params['saleman'] = $list;
        $model                             = new InquiryType();
        $inquiryType                       = $model->list();
        $model                             = new CustomerRefer();
        $customerRefer                     = $model->list();

        yii::$app->view->params['customerRefer'] = $customerRefer;
        yii::$app->view->params['inquiryType']   = $inquiryType;

        return $this->render('/inquiry/inquiry');
    }

    /**
     * 询盘管理
     */
    public function actionInquiry_list()
    {
        $p                       = is_numeric(yii::$app->request->get('p')) ? yii::$app->request->get('p') : 1;
        $s                       = is_numeric(yii::$app->request->get('s')) ? yii::$app->request->get('s') : 15;
        $where['name']           = trim(yii::$app->request->get('customer_name'));
        $where['inquiry_detail'] = trim(yii::$app->request->get('inquiry_detail'));
        $where['email']          = trim(yii::$app->request->get('email'));
        $where['begin_time']     = yii::$app->request->get('begin_time');
        $where['end_time']       = yii::$app->request->get('end_time');
        $where['star']           = yii::$app->request->get('star');
        $where['recommend']      = yii::$app->request->get('recommend');
        $where['service_name']   = yii::$app->request->get('service_name');
        $where['status']         = yii::$app->request->get('status');
        $where['property']       = yii::$app->request->get('property');
        $where['refer']          = yii::$app->request->get('refer');
        if ($this->user['role'] != 1) {
            $where['service_name'] = $this->user['job_number'];
        }
        if ($this->user['job_number'] == 7) {
            $where['service_name'] = [7, 22];
        }
        $model = new Inquiry();
        $size  = $model->get_inquiry_size($where);
        $page  = $size ? (ceil($size / $s)) : 1;
        $list  = $model->get_inquiry_list($p, $s, $where);
        $chart = $model->inquiryRecommendGroup($where);

        $staff         = new Staff();
        $staff_list    = $staff->get_staff_list();
        $model         = new InquiryType();
        $inquiryType   = $model->list();
        $model         = new CustomerRefer();
        $customerRefer = $model->list();
        $title         = [];
        foreach ($chart as $k => $v) {
            foreach ($customerRefer as $v2) {
                if ($v['recommend'] == $v2['id']) {
                    $title[]            = $v2['name'];
                    $chart[$k]['name']  = $v2['name'];
                    $chart[$k]['value'] = $v['num'];
                }
            }
        }
        yii::$app->view->params['customerRefer'] = $customerRefer;
        yii::$app->view->params['inquiryType']   = $inquiryType;
        yii::$app->view->params['staff_list']    = $staff_list;
        $base_url                                = Url::to(['setting/inquiry_list']) . $this->get_base_url();
        yii::$app->view->params['list']          = $list;
        yii::$app->view->params['page']          = ['page' => $page, 'curr' => $p, 'base_url' => $base_url];
        return $this->render('/inquiry/inquiry_list', ['chart' => $chart, 'title' => $title]);
    }

    /**下载询盘excel
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function actionDownloadInquiryExcel()
    {
        $where['name']           = trim(yii::$app->request->get('customer_name'));
        $where['inquiry_detail'] = trim(yii::$app->request->get('inquiry_detail'));
        $where['email']          = trim(yii::$app->request->get('email'));
        $where['begin_time']     = yii::$app->request->get('begin_time');
        $where['end_time']       = yii::$app->request->get('end_time');
        $where['star']           = yii::$app->request->get('star');
        $where['recommend']      = yii::$app->request->get('recommend');
        $where['service_name']   = yii::$app->request->get('service_name');
        $where['status']         = yii::$app->request->get('status');
        $where['property']       = yii::$app->request->get('property');
        $where['refer']          = yii::$app->request->get('refer');
        $model                   = new Inquiry();
        $list                    = $model->getInquiryList($where);

        $staff         = new Staff();
        $staff_list    = $staff->get_staff_list();
        $model         = new InquiryType();
        $inquiryType   = $model->list();
        $model         = new CustomerRefer();
        $customerRefer = $model->list();
        foreach ($list as $k => $v) {
            foreach ($staff_list as $v2) {
                if ($v['service_name'] == $v2['job_number']) {
                    $list[$k]['service_name'] = $v2['name'];
                    break;
                }
            }
            foreach ($inquiryType as $v2) {
                if ($v['refer'] == $v2['id']) {
                    $list[$k]['refer'] = $v2['name'];
                    break;
                }
            }
            foreach ($customerRefer as $v2) {
                if ($v['recommend'] == $v2['id']) {
                    $list[$k]['recommend'] = $v2['name'];
                    break;
                }
            }
        }

        $excel = new \PHPExcel();

        $excel->setActiveSheetIndex(0)
            ->setCellValue('A1', '询盘来源')
            ->setCellValue('B1', '询盘日期')
            ->setCellValue('C1', '客户编号')
            ->setCellValue('D1', '客户名称')
            ->setCellValue('E1', '邮箱')
            ->setCellValue('F1', '推荐人')
            ->setCellValue('G1', '国家')
            ->setCellValue('H1', '业务员')
            ->setCellValue('I1', '分配状态')
            ->setCellValue('J1', '星级')
            ->setCellValue('K1', '询盘信息')
            ->setCellValue('L1', '是否下单');
        $orderStatus = [1 => '未下单', 2 => '样品单', 3 => '已下单'];
        foreach ($list as $k => $v) {
            $num = $k + 2;

            //Excel的第A列，uid是你查出数组的键值，下面以此类推
            $excel->setActiveSheetIndex(0)->setCellValue('A' . $num, $v['refer']);
            $excel->setActiveSheetIndex(0)->setCellValue('B' . $num, date('Y-m-d', $v['consultation_time']));
            $excel->setActiveSheetIndex(0)->setCellValue('C' . $num, $v['customer_num']);
            $excel->setActiveSheetIndex(0)->setCellValue('D' . $num, $v['name']);
            $excel->setActiveSheetIndex(0)->setCellValue('E' . $num, $v['email']);
            $excel->setActiveSheetIndex(0)->setCellValue('F' . $num, $v['recommend']);
            $excel->setActiveSheetIndex(0)->setCellValue('G' . $num, $v['country']);
            $excel->setActiveSheetIndex(0)->setCellValue('H' . $num, $v['service_name']);
            if ($v['status'] == 1) {
                $excel->setActiveSheetIndex(0)->setCellValue('I' . $num, '未分配');
            } else if ($v['status'] == 2) {
                $excel->setActiveSheetIndex(0)->setCellValue('I' . $num, '以分配');
            } else if ($v['status'] == 3) {
                $excel->setActiveSheetIndex(0)->setCellValue('I' . $num, '拒绝');
            };

            $excel->setActiveSheetIndex(0)->setCellValue('J' . $num, $v['star'] . '星');
            $excel->setActiveSheetIndex(0)->setCellValue('K' . $num, $v['inquiry_detail']);
            $excel->setActiveSheetIndex(0)->setCellValue('L' . $num, $orderStatus[$v['property']]);

        }
        $name = 'inquiry';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $name . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($excel, 'Excel5');
        $objWriter->save('php://output');
    }

    /**
     * 删除询盘
     */
    public function actionDel_inquiry()
    {
        $id = is_numeric(yii::$app->request->post('id')) ? yii::$app->request->post('id') : "";
        if ($id) {
            $model = new Inquiry();
            $re    = $model->delete(['id' => $id]);
            if ($re) {
                echo json_encode(['code' => 1, 'msg' => '更新成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '更新失败,请重试']);
            }
        }
    }

    /**
     * @return yii\web\Response
     */
    public function actionInquiry_act_add()
    {
        $data                      = $_POST;
        $data['consultation_time'] = strtotime($data['consultation_time']);
        $data['reply_time']        = strtotime($data['reply_time']);

        $model = new Customer();
        //生成客户编号

        if ($re = $model->get_number_by_email($data['email'])) {
            $data['customer_num'] = $re['number'];
        }

        $model = new Inquiry();
        $re    = $model->insert($data);
        if ($re == 1) {
            return $this->redirect(Url::to(['setting/inquiry_list']));
        } else {
            return $this->redirect(Url::to(['setting/inquiry']));
        }
    }

    /**上传询盘excel
     * @return bool
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     */
    public function actionInquiry_upload_excel()
    {
        $path = $this->get_folder();
        $file = $_FILES['file'];
        $list = (new yii\db\Query())->select('server_num,job_number')
            ->from(yii::$app->db->tablePrefix . "staff")
            ->where(['status' => 0])
            ->all();
        if ($file) {
            $suffix = explode(".", $file['name']);
            if (!($suffix[1] == 'xls' || $suffix[1] == 'xlsx')) {
                echo json_encode(['code' => 0, 'msg' => '不是excel文件']);
                return false;
            }
            $real_path = $path . DIRECTORY_SEPARATOR . "inquiry_" . time() . "." . $suffix[1];
            $re        = move_uploaded_file($file['tmp_name'], $real_path);
            if ($re) {
                //获取excel对象
                $objPHPExcel   = $this->get_excel($real_path, $suffix[1]);
                $sheet         = $objPHPExcel->getSheet(0);
                $highestRow    = $sheet->getHighestRow();
                $highestColumn = $sheet->getHighestColumn();
            }
            //从第二行开始读取
            $data = [];
            for ($j = 2; $j <= $highestRow; $j++) {
                $num = (string) $objPHPExcel->getActiveSheet()->getCell("B$j")->getValue();
                if ($num) {
                    $data[$j][] = $num;
                    $data[$j][] = $objPHPExcel->getActiveSheet()->getCell("K$j")->getValue();

                    $time1 = $objPHPExcel->getActiveSheet()->getCell("D$j")->getValue();
                    if ($time1 && gettype($time1) !== 'string') {
                        $data[$j][] = abs(($time1 - 25569) * 24 * 60 * 60);
                    } else {
                        $data[$j][] = "";
                    }

                    $time2 = $objPHPExcel->getActiveSheet()->getCell("F$j")->getValue();
                    if ($time2 && gettype($time2) !== 'string') {
                        $data[$j][] = abs(($time2 - 25569) * 24 * 60 * 60);
                    } else {
                        $data[$j][] = "";
                    }

                    $time3 = $objPHPExcel->getActiveSheet()->getCell("H$j")->getValue();
                    if ($time3 && gettype($time3) !== 'string') {
                        $data[$j][] = abs(($time3 - 25569) * 24 * 60 * 60);
                    } else {
                        $data[$j][] = "";
                    }

                    $data[$j][] = (string) $objPHPExcel->getActiveSheet()->getCell("C$j")->getValue();
                    $data[$j][] = (string) $objPHPExcel->getActiveSheet()->getCell("J$j")->getValue();
                    $data[$j][] = (string) $objPHPExcel->getActiveSheet()->getCell("U$j")->getValue();
                    $data[$j][] = (string) $objPHPExcel->getActiveSheet()->getCell("L$j")->getValue();
                    $data[$j][] = (string) $objPHPExcel->getActiveSheet()->getCell("M$j")->getValue();
                    $data[$j][] = (string) $objPHPExcel->getActiveSheet()->getCell("N$j")->getValue();
                    $data[$j][] = (string) $objPHPExcel->getActiveSheet()->getCell("O$j")->getValue();
                    $data[$j][] = (string) $objPHPExcel->getActiveSheet()->getCell("P$j")->getValue();
                    $data[$j][] = (int) $objPHPExcel->getActiveSheet()->getCell("Q$j")->getValue();
                    $time4      = $objPHPExcel->getActiveSheet()->getCell("R$j")->getValue();
                    $data[$j][] = abs(($time4 - 25569) * 24 * 60 * 60 + $objPHPExcel->getActiveSheet()->getCell("S$j")->getValue());
                    $status     = (string) $objPHPExcel->getActiveSheet()->getCell("T$j")->getValue();
                    if ($status == '待分配') {
                        $data[$j][] = 1;
                    } elseif ($status == '已分配') {
                        $data[$j][] = 2;
                    } elseif ($status == '拒绝') {
                        $data[$j][] = 3;
                    } else {
                        $data[$j][] = 1;
                    }
                }
            }
            $service = new CustomerService();
            $re      = $service->insert($data);
            if ($re) {
                echo json_encode(['code' => 1, 'msg' => '添加成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '添加失败，请重试']);
            }
        }
    }

    /**询盘编辑页面
     * @return string
     */
    public function actionInquiry_edit()
    {
        $id = yii::$app->request->get('id');
        if (is_numeric($id)) {
            $model                          = new Inquiry();
            $info                           = $model->one(['id' => $id]);
            yii::$app->view->params['info'] = $info;
            $staff_model                    = new Staff();
            $saleman                        = $staff_model->get_all_saleman();

            $model       = new InquiryType();
            $inquiryType = $model->list();

            $model         = new CustomerRefer();
            $customerRefer = $model->list();

            yii::$app->view->params['customerRefer'] = $customerRefer;
            yii::$app->view->params['inquiryType']   = $inquiryType;
            yii::$app->view->params['saleman']       = $saleman;
            return $this->render('/inquiry/inquiry_edit');
        } else {
            echo "<script>alert('非法请求');window.history.go(-1);</script>";
        }
    }

    public function actionInquiry_edit_act()
    {
        $data                      = $_POST['data'];
        $id                        = yii::$app->request->post('id');
        $data['consultation_time'] = strtotime($data['consultation_time']);
        $data['reply_time']        = strtotime($data['reply_time']);
        $data['dispatch_time']     = strtotime($data['dispatch_time']);
        //判断是否生成客户数据
        if (isset($data['status'])) {
            if ($data['status'] == 2) {
                //判断当前email是否存在
                $customerModel = new Customer();
                if (!$customerModel->searchByEmail($data['email'])) {
                    $arr                  = [];
                    $arr['customer_name'] = $data['name'];
                    $arr['email']         = $data['email'];
                    $arr['follow_man']    = $data['service_name'];
                    $arr['customer_star'] = $data['star'];
                    $arr['country']       = $data['country'];
                    $num                  = $customerModel->getMaxNumV2();
                    $num++;
                    $arr['number']    = 'K' . date('ymd') . str_pad($num, 3, 0, STR_PAD_LEFT);
                    $arr['refer']     = $data['recommend'];
                    $arr['create_at'] = date('Y-m-d');
                    $customerModel->insert($arr);
                }
            }
        }
        $model = new Inquiry();
        $re    = $model->save($data, ['id' => $id]);
        if ($re == 1) {
            echo json_encode(['code' => 1, 'msg' => '修改成功']);
        } else {
            echo json_encode(['code' => 0, 'msg' => '修改失败,请重试']);
        }
    }

    /**权限列表
     * @return string
     */
    public function actionAction_list()
    {
        $model                          = new \app\models\Modules();
        $list                           = $model->get_all_action_list();
        $tree                           = $this->get_tree($list);
        yii::$app->view->params['list'] = $tree;
        return $this->render('action_list');
    }

    /**权限添加
     * @throws yii\db\Exception
     */
    public function actionAction_add()
    {
        $data = $_POST;

        $model = new \app\models\Modules();
        $info  = $model->get_action_by_id($data['id']);

        $data['list'] = $info['list'] . "-" . $info['id'];
        $data['pid']  = $info['id'];
        unset($data['id']);

        $re = yii::$app->db->createCommand()->insert(yii::$app->db->tablePrefix . "modules", $data)->execute();
        if ($re) {
            echo json_encode(['code' => 1, 'msg' => '添加成功']);
        } else {
            echo json_encode(['code' => 0, 'msg' => '添加失败，请重试']);
        }
    }

    public function actionAuth()
    {
        //获取角色列表
        $rolelist = (new \yii\db\Query())->select('*')
            ->from(yii::$app->db->tablePrefix . "adminrole")
            ->all();
        //当前角色所有rule
        $role      = yii::$app->request->get('role') ? yii::$app->request->get('role') : 1;
        $rule_list = [];
        foreach ($rolelist as $k => $v) {
            if ($v['id'] == $role) {
                $rule_list = explode(',', $v['role_rules']);
                break;
            }
        }
        $model = new \app\models\Modules();
        $list  = $model->get_all_action_list();
        $tree  = $this->get_tree($list);

        yii::$app->view->params['rules']    = $rule_list;
        yii::$app->view->params['list']     = $tree;
        yii::$app->view->params['role']     = $role;
        yii::$app->view->params['rolelist'] = $rolelist;
        return $this->render('auth');
    }

    public function actionUpdate_role_rules()
    {
        $rules = $_POST['rules'];
        $role  = $_POST['role'];
        if (is_numeric($role)) {
            $model = new \app\models\Modules();
            $re    = $model->update_rule_by_role($role, implode(',', $rules));

            if ($re) {
                $user_id     = $this->user['id'];
                $model       = new \app\models\AdminUser();
                $update_user = $model->get_user_by_id($user_id);
                $redis       = $this->getInstance();
                $redis_key   = 'user:' . $user_id;
                $redis->delete('role_rules');
                $redis->setex($redis_key, 3600 * 12, json_encode($update_user));
                echo json_encode(['code' => 1, 'msg' => '更新成功']);
            } else {
                echo json_encode(['code' => 1, 'msg' => '更新失败，请重试']);
            }
        }
    }

    public function actionAccount()
    {
        $model                          = new \app\models\AdminUser();
        $list                           = $model->get_all_user();
        yii::$app->view->params['list'] = $list;
        $role                           = $model->get_admin_role();
        yii::$app->view->params['role'] = $role;

        //所有员工
        $model       = new \app\models\Staff();
        $staff       = $model->get_staff_list();
        $hasRegister = array_column($list, 'staff_id');
        $arr         = [];
        foreach ($staff as $v) {
            if ((int) $v['status'] === 0) {
                if (!in_array($v['id'], $hasRegister)) {
                    $arr[] = $v;
                }
            }
        }
        yii::$app->view->params['staff_list'] = $arr;

        return $this->render('account');
    }

    public function actionAdd_adminuser()
    {
        $data['name']     = yii::$app->request->post('name');
        $data['password'] = md5(yii::$app->request->post('password'));
        $data['role']     = yii::$app->request->post('role');
        $data['staff_id'] = yii::$app->request->post('staff_id');
        $data['time']     = time();
        if (!(is_numeric($data['role']) && is_numeric($data['staff_id']))) {
            echo json_encode(['code' => 0, 'msg' => '非法请求']);
            return false;
        }
        $model = new AdminUser();
        //判断职员是否绑定
        if ($model->get_adminuser_by_staff_id($data['staff_id'])) {
            echo json_encode(['code' => 0, 'msg' => '该职员已被绑定']);
            return false;
        }

        //账号是否被使用
        if ($model->get_adminuser_by_name($data['name'])) {
            echo json_encode(['code' => 0, 'msg' => '该账号名称已被使用']);
            return false;
        }

        if ($model->add_admin_user($data)) {
            echo json_encode(['code' => 1, 'msg' => '添加成功']);
        } else {
            echo json_encode(['code' => 0, 'msg' => '添加失败,请重试']);
        }
    }

    /**报销列表
     * @return string
     */
    public function actionReimburse()
    {
        $p                              = is_numeric(yii::$app->request->get('p')) ? yii::$app->request->get('p') : 1;
        $s                              = is_numeric(yii::$app->request->get('s')) ? yii::$app->request->get('s') : 15;
        $model                          = new Baoxiao();
        $where                          = [];
        $where['job_number']            = $this->user['job_number'];
        $list                           = $model->all($where, ($p - 1) * $s, $s, ['create_at' => SORT_DESC]);
        $size                           = $model->get_baoxiao_size($where);
        $sum                            = $model->caculateData($where);
        $page                           = $size ? ceil($size / $s) : 1;
        $url                            = '/setting/reimburse' . $this->get_base_url();
        yii::$app->view->params['page'] = ['curr' => $p, 'page' => $page, 'url' => $url];

        return $this->render('reimburse_list', ['list' => $list, 'money' => $sum]);

    }

    /**上传报销
     * @throws yii\db\Exception
     */
    public function actionUpload_baoxiao()
    {
        $data             = $_POST['data'];
        $data2            = json_decode($data, true);
        $table            = yii::$app->db->tablePrefix . "baoxiao";
        $data2['invoice'] = isset($data2['invoice']) ? $data2['invoice'] : '';
        $insert_data      = [
            'detail'        => $data,
            'fee'           => $data2['fee'],
            'job_number'    => $this->user['job_number'],
            'invoice'       => $data2['invoice'],
            'type'          => $data2['type'],
            'type2'         => $data2['type2'],
            'customer_num'  => $data2['customer_num'],
            'customer_name' => $data2['customer_name'],
            'create_at'     => date('Y-m-d'),
        ];
        $re = yii::$app->db->createCommand()->insert($table, $insert_data)->execute();
        if ($re) {
            echo json_encode(['code' => 1, 'msg' => '添加成功']);
        } else {
            echo json_encode(['code' => 0, 'msg' => '添加失败，请重试']);
        }
    }

    //历史报销单
    public function actionReimburseAdd()
    {
        $model                          = new Customer();
        $where                          = [];
        $where['follow_man']            = $this->user['job_number'];
        $list                           = $model->get_all_customer($where);
        yii::$app->view->params['list'] = $list;
        return $this->render('reimburse');
    }

    /**
     * 报销编辑
     */
    public function actionReimburseEdit()
    {
        if (yii::$app->request->isPost) {
            $id = yii::$app->request->post('id');
            //检查是否已经审核成功
            $model = new Baoxiao();
            $info  = $model->one(['id' => $id]);
            if ($info['status'] == 2) {
                return json_encode(['code' => 0, 'msg' => '已经审核成功，无需提交']);
            }
            $param = yii::$app->request->post('param');
            $value = yii::$app->request->post('value');

            $re = $model->save([$param => $value], ['id' => $id]);
            if ($re) {
                echo json_encode(['code' => 1, 'msg' => '添加成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '修改失败,请重试']);
            }
        }
    }

//个人中心-我的业绩
    public function actionAchievement()
    {
        return $this->render('achievement');
    }

//个人资料设置
    public function actionInfo()
    {
        return $this->render('info');
    }

    public function actionUpdate_pd()
    {
        if (yii::$app->request->isPost) {
            $password     = yii::$app->request->post('password');
            $loginService = new LoginService();
            $re           = $loginService->updateUser($this->user['id'], $password);
            if ($re) {
                //删除cookie
                $cookie = yii::$app->request->cookies->get('jwt');
                yii::$app->response->getCookies()->remove($cookie);
                echo json_encode(['code' => 1, 'msg' => '更新成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '更新失败，请重试']);
            }
        }
    }

//采购业务员关系表
    public function actionPurchases_saleman()
    {
        $model = new Staff();
        $list  = $model->get_purchases_saleman();
        //echo json_encode($list);exit;
        yii::$app->view->params['list'] = $list;
        return $this->render('purchase_relation_saleman');
    }

    public function actionUpdate_purchases_saleman()
    {
        if (yii::$app->request->isPost) {
            $data     = yii::$app->request->post('data');
            $purchase = yii::$app->request->post('purchase');
            $model    = new Staff();
            $re       = $model->update_purchase_saleman($data, $purchase);
            if ($re) {
                echo json_encode(['code' => 1, 'msg' => '修改成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '修改失败，请重试']);
            }
        }
    }

    /**
     * 发送广播
     */
    public function actionBroadcast()
    {
        $service                              = new StaffService();
        $staff_list                           = $service->all_staff();
        $broadcastService                     = new BroadcastService();
        $group                                = $broadcastService->get_group();
        yii::$app->view->params['group']      = $group;
        yii::$app->view->params['staff_list'] = $staff_list;
        return $this->render('broadcast');
    }

    /**
     * 添加广播分组
     */
    public function actionBroadcast_add()
    {
        if (yii::$app->request->isPost) {
            $data['group_name'] = yii::$app->request->post('group_name');
            $data['staff']      = yii::$app->request->post('staff');
            if (!$data['staff']) {
                unset($data['staff']);
            }
            if ($data['group_name']) {
                $service = new BroadcastService();
                $re      = $service->insert($data);
                if ($re) {
                    echo json_encode(['code' => 1, 'msg' => '添加成功']);
                } else {
                    echo json_encode(['code' => 0, 'msg' => '添加失败']);
                }
            }
        }
    }

    /**
     * 发送广播操作
     */
    public function actionBroadcast_act()
    {
        if (yii::$app->request->isPost) {
            $data['group_id'] = yii::$app->request->post('group_id');
            $data['msg']      = yii::$app->request->post('msg');
            if ($data['group_id'] && $data['msg']) {
                $data['job_number'] = $this->user['job_number'];
                $service            = new BroadcastService();
                $data['create_at']  = time();
                $re                 = $service->insert_broadcast($data);
                if ($re) {
                    echo json_encode(['code' => 1, 'msg' => '添加成功']);
                } else {
                    echo json_encode(['code' => 0, 'msg' => '添加失败']);
                }
            }
        }
    }

    /**
     * 广播组编辑
     */
    public function actionBroadcast_group()
    {
        $service    = new BroadcastService();
        $group      = $service->get_group();
        $service    = new StaffService();
        $staff_list = $service->all_staff();
        foreach ($group as $k => $v) {
            $group[$k]['staff'] = json_decode($v['staff'], true);
        }
        //echo json_encode($group);exit;
        yii::$app->view->params['group'] = $group;
        yii::$app->view->params['staff'] = $staff_list;
        return $this->render('broadcast_group');
    }

    /**
     * 更新分组信息
     */
    public function actionUpdate_broadcast_group()
    {
        if (yii::$app->request->isPost) {
            $id            = yii::$app->request->post('group');
            $data['staff'] = json_encode(yii::$app->request->post('staff'));
            $table         = yii::$app->db->tablePrefix . 'broadcast_group';
            $re            = yii::$app->db->createCommand()->update($table, $data, ['id' => $id])->execute();
            if ($re) {
                echo json_encode(['code' => 1, 'msg' => '修改成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '修改失败，请重试']);
            }
        }
    }

    public function actionNotice()
    {
        return $this->render('notice');
    }

    public function actionAdd_announce()
    {
        $file          = yii::$app->request->post('file');
        $title         = yii::$app->request->post('title');
        $data          = [];
        $data['file']  = $file;
        $data['title'] = $title;
        $data['staff'] = $this->user['job_number'];
        $data['time']  = time();
        $model         = new Announce();
        $re            = $model->insert($data);
        $outpout       = $re ? ['code' => 1, ''] : ['code' => 0, 'msg' => '1100'];
    }

    /**
     *top10产品界面
     *
     */
    public function actionTop10Product()
    {

        $page     = yii::$app->request->get('page', 1);
        $pageSize = yii::$app->request->get('per-page', 10);
        $type     = yii::$app->request->get('type', 1);
        if ($type == 1) {
            $where    = [];
            $model    = new LandEmail();
            $list     = $model->all($where, ($page - 1) * $pageSize, $pageSize, ['time' => SORT_DESC]);
            $size     = $model->size($where);
            $ipsearch = new \app\lib\Ip2Region(ROOT_PATH . '/ip2region.db');
            foreach ($list as $key => $value) {
                $city               = $ipsearch->memorySearch($value['ip']);
                $list[$key]['city'] = $city['region'];
            }
        } elseif ($type == 2) {
            $where          = [];
            $where['refer'] = 24;
            $model          = new Customer();
            $list           = $model->get_customer_list($page, $pageSize, $where);
            $size           = $model->get_customer_size($where);
            $customerId     = array_column($list, 'id');
            $db             = new \yii\db\Query();
            $inquiryList    = $db->select('user_id')->from('jingsourcing_new_inquiry')->where(['in', 'user_id', $customerId])->all();
            foreach ($list as $k => $v) {
                if (in_array($v['id'], $inquiryList)) {
                    $list[$k]['have_inquiry'] = true;
                } else {
                    $list[$k]['have_inquiry'] = false;
                }
            }
        }
        $pagination = new yii\data\Pagination(['totalCount' => $size, 'pageSize' => 10]);
        return $this->render('top10', ['type' => $type, 'page' => $pagination, 'list' => $list]);
    }
}
